package com.kaifamiao.servlet;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.logging.Logger;

public class PrimitiveServlet implements Servlet {

    private static final Logger logger = Logger.getGlobal();

    static {
        logger.info( "初始化PrimitiveServlet类" );
    }

    private ServletConfig config;

    public PrimitiveServlet(){
        super();
        logger.info( "创建PrimitiveServlet实例" );
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        logger.info( "初始化`servlet`实例: " + this );
        this.config = config;
    }

    @Override
    public void service(ServletRequest req, ServletResponse resp)
            throws ServletException, IOException {
        logger.info( "[" + this + "]提供服务" );

        // 设置 响应 的 MIME类型
        resp.setContentType( "text/html;charset=UTF-8");
        // 获得可以向 响应对象 中输出数据的 字符打印流
        PrintWriter out = resp.getWriter();

        out.println( "<link rel=\"stylesheet\" href=\"/styles/index.css\">");

        // 将 字符数据 打印到 响应对象 的缓冲区中
        out.println( "<div class=\"wrapper\">");
        out.println( LocalDateTime.now() );
        out.println( "</div>" );
    }

    @Override
    public void destroy() {
        logger.info( "释放[" + this + "]所占用的资源" );
    }

    @Override
    public String getServletInfo() {
        return config.getServletName();
    }

    @Override
    public ServletConfig getServletConfig() {
        return config;
    }
}